package com.powernode.listener;

import cn.hutool.json.JSONUtil;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.powernode.constant.QueueConstant;
import com.powernode.service.SmsLogService;
import com.powernode.utils.MsgUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class AliMsgListener {
    @Autowired
    private SmsLogService smsLogService;

    @RabbitListener(queues = QueueConstant.PHONE_CODE_QUEUE)
    public void aliMsgHandler(Message message, Channel channel) {
        // 获取消息
        String codeMessage = new String(message.getBody());
        HashMap map = JSONUtil.toBean(codeMessage, HashMap.class);

        // 调用短信接口
        SendSmsResponse sendSmsResponse = MsgUtil.sendMessage((String) map.get("regionId"),
                (String) map.get("accessKeyId"),
                (String) map.get("secret"),
                (String) map.get("signName"),
                (String) map.get("templateCode"),
                (String) map.get("mobile"),
                (String) map.get("param"));

        if (sendSmsResponse != null && "OK".equals(sendSmsResponse.getCode())
                && "OK".equals(sendSmsResponse.getMessage())) {
            smsLogService.saveCodeLog(map);
        }

        // 签收消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
